﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebConversion.Module.MemberShip;
using WebConversion.Mvc.Models;

namespace WebConversion.Mvc.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            try
            {
                if (!ModelState.IsValid
                    || !UserProfile.ValidUser(model.EMail, model.Password))
                {
                    throw new MemberAccessException();
                }

                var userProfile = UserProfile.GetUserByEMail(model.EMail);

                SetCookie(userProfile, model.RememberMe);

                return RedirectToAction("Index", "Home");
            }
            catch (MemberAccessException)
            {
                ModelState.AddModelError("", ErrorCodeToString(MembershipCreateStatus.InvalidUserName));
            }

            return View(model);
        }

        private void SetCookie(UserProfile loginUser, bool isRememberMe)
        {
            var userData = loginUser.GUID;
            var ticket =
                new FormsAuthenticationTicket(
                    1,
                    loginUser.FirstName,
                    DateTime.Now,
                    DateTime.Now.AddDays(1),
                    isRememberMe,
                    userData,
                    FormsAuthentication.FormsCookiePath
                    );

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));
        }

        // POST: /Account/LogOff
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (UserProfile.IsRegisted(model.EMail))
                    {
                        throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateEmail);
                    }

                    var userProfile =
                        new UserProfile()
                            {
                                FirstName = model.FirstName,
                                LastName = model.LastName,
                                EMail = model.EMail,
                                Password = model.Password,
                                Address = model.Address
                            };

                    userProfile.Create();

                    SetCookie(userProfile, false);

                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            return View(model);
        }

        // GET: /Account/Manage
        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";

            ViewBag.HasLocalPassword = !string.IsNullOrEmpty(GetGUIDFromCookie());

            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        private string GetGUIDFromCookie()
        {
            var ticket = ((FormsIdentity)User.Identity).Ticket;
            var userData = ticket.UserData;
            return userData;
        }

        // POST: /Account/Manage
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                bool changePasswordSucceeded;
                try
                {
                    changePasswordSucceeded = UserProfile.ChangePassword(GetGUIDFromCookie(), model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                }

                ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
            }

            return View(model);
        }

        #region Helpers

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            RemoveLoginSuccess,
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
